<?php
/**
 * 推荐位管理
 * Created by Sublime Text 3.
 * @authors Rejeo (rejeo@qq.com)
 * @date    2018-05-03 13:25:17
 * @version $Id$
 */
namespace app\admin\controller;

use think\Controller;
use think\Request;
use app\common\model\Featured as FeaturedModel;

class Featured extends Controller
{
    private $link;
    private $types;

    public function _initialize()
    {
        $this->link = new FeaturedModel();
        $this->types = config('featured.featured_type');
    }

    public function index(Request $request)
    {
        $type = $request->get('type');
        $res = $this->link->getFeaturedByType($type);
        $page = $res->render();
        return $this->fetch('', [
            'types' => $this->types,
            'type' => $type,
            'res' => $res,
            'page'=> $page,
        ]);
    }

    public function add(Request $request)
    {
        if ($request->isPost()) {
            $data = $request->post();
            // 做数据的校验
            // $vali = $this->validate();
            // if (TRUE !== $vali) {
            //     $this->error($vali);
            // }
            $res = $this->link->add($data);
            if ($res) {
                $this->success('添加推荐位成功！');
            }
            $this->error('数据提交有误！');
        }

        // dump($types);
        return $this->fetch('', [
            'types' => $this->types,
        ]);
    }

    // 状态修改
    public function status(Request $request)
    {
        $data = $request->get();
        $rule = [
            'id'        => 'number',
            'status'    => 'number|in:-1,0,1,2'
        ];
        $validate = $this->validate($data,$rule);// 实例化验证规则
        if(TRUE !== $validate){
            $this->error($validate);
        }
        $res = $this->link->save(['status'=>$data['status']],['id'=>$data['id']]);
        if ($res) {
            $this->success('状态设置成功！');
        }
        $this->error('状态设置失败！');
    }
}
